public class SendOrder {
  
    @Future(callout=true)
    public static void SendOrderToDistributor(Id orderId)
    {
        Order__c order=[select Id,Name,Total_value__c,Distributor_Name__c,OrderType__c,Outlet_name__c,Address__c,Order_date__c,Time_to_delivered__c from Order__c where Id=:orderId];
        List<Order_Item__c> oItem=[select Id,Product_Name__c,ReturnReasonList__c,OrderNumber__c,Return_Reason__c,Product_Name__r.Product_Unit_Volume__c,RealItemNumber__c,RealPackage__c,Price_after_tax__c from Order_Item__c where Order_Name__c=:orderId];
        if(order != NULL)
        {
            //if(order.OrderType__c=='退货' || order.OrderType__c=='免费产品')
           // {
                Distributor__c dis=[Select Name, Fax__c, Email__c, Accepted_Order_Way__c From Distributor__c where Id=:order.Distributor_Name__c];
                Account acc=[Select OutletCode__c, Outlet_Address__c, Name,Owner.Name From Account where Id=:order.Outlet_name__c];
                String sendType=dis.Accepted_Order_Way__c;
               
                if(sendType!=null && sendType=='Email')
                {
                     SendMail(order,oItem,dis,acc);
                }
                if(sendType!=null && sendType=='Fax')
                {
                     SendFax(order,oItem,dis,acc);
                }
           // }
        }
        //return '';
    }
    public static String SendMail(Order__c order,List<Order_Item__c> oItem,Distributor__c dis,Account acc)
    {
        String mailStr;
         String DisMail=dis.Email__c;
         if(DisMail!=null)
         {
            String BodyString=getBodyString(order,OItem,dis,acc);
            Messaging.Singleemailmessage mail=new Messaging.Singleemailmessage();
            String[] ToAddress=new String[]{DisMail};
            mail.setToAddresses(ToAddress);
            mail.setSubject('订单');
            mail.setSenderDisplayName('订单');
            mail.setHtmlBody(BodyString);
            mail.setPlainTextBody(BodyString);
            mail.setUseSignature(false);
            //Messaging.EmailFileAttachment[] fileAttachments = new Messaging.EmailFileAttachment[1];
            Messaging.Emailfileattachment att=new Messaging.Emailfileattachment();
            List<Attachment> fileList=[select Body from Attachment where ParentId=:order.Id order by CreatedDate asc limit 1];
            if(fileList!=NULL && fileList.size()>0)
            {
                Attachment file=fileList.get(0);
                att.setBody(file.Body);
                att.setFileName('电子签名.bmp');
                //att..getContentType();
                Messaging.EmailFileAttachment[] fileAttachments = new Messaging.EmailFileAttachment[1];
                fileAttachments[0]=att;
                //fileAttachments[0].setContentType('ffff');
                mail.setFileAttachments(fileAttachments);
            }
           // mail.setFileAttachments(new Messaging.Emailfileattachment())
            try
            {
                Messaging.sendEmail(new Messaging.Singleemailmessage[]{mail});
                mailStr='用邮件方式发送订单到经销商成功';
            }
            catch(EmailException ex)
            {
                mailStr='用邮件方式发送订单到经销商失败'+ex.getMessage();
            }
        }
        return mailStr;
    }
    
    public static String SendFax(Order__c order,List<Order_Item__c> oItem,Distributor__c dis,Account acc)
    {
        String body;
        String fax=dis.Fax__c;
        if(fax != NULL)
        {
             List<Attachment> fileList=[select Body from Attachment where ParentId=:order.Id order by CreatedDate asc limit 1];
             
             String html = getBodyString(order,oItem,dis,acc);
          
            String fileName = 'Fax.html';
           ExternalWebServiceConfiguration__c ex=ExternalWebServiceConfiguration__c.getValues('HiFax');
           
            String fileEncoding =EncodingUtil.base64Encode(Blob.valueOf(html));
            /*modify by xiaojiang 100915*/
            if(fileList.size()<=0)
            {
                return ' ';
            }
            /*end modify*/
            String xml = createXML(String.valueOf(ex.UserName_del__c),String.valueOf(ex.Password__c),String.valueOf(ex.AccessKey__c),fileName,fileEncoding,dis,fileList);
            try
            {
                HiFaxCallOut.FaxServiceSoap c = new HiFaxCallOut.FaxServiceSoap();
                body = c.SendFax(xml);
                body='用传真发送订单到经销商成功';
            }
            catch(CalloutException e)
            {
                body='用传真发送订单到经销商失败'+e.getMessage();
            }
        }
        return body;
    }
    
     private static String createXML(String userName,String pwd,String key,String fileName,String fileEncoding,Distributor__c dis,List<Attachment> fileList)
     {
        String xml = '<?xml version="1.0" encoding="UTF-8"?>';
        xml += '<SendFaxReq>';
        xml += '<Head>';
        xml += '<UserInfo>';
        xml += '<UserName>'+userName+'</UserName>';
        xml += '<Password>'+pwd+'</Password>';
        xml += '<Accresskey>'+key+'</Accresskey>';
        xml += '</UserInfo>';
        xml += '</Head>';
        xml += '<Body>';
        xml += '<SendFileList>';
        xml += '<SendFile>';
        xml += '<FileName>' + fileName + '</FileName>';
        xml += '<FileEncoding>' + fileEncoding + '</FileEncoding>';
        xml += '</SendFile>';
        if(fileList!=NULL && fileList.size()>0)
        {
            xml += '<SendFile>';
            xml += '<FileName>电子签名.bmp</FileName>';
            xml += '<FileEncoding>' + EncodingUtil.base64Encode(fileList.get(0).Body)+ '</FileEncoding>';
            xml += '</SendFile>';
        }
        xml += '</SendFileList>';
        xml += '<RecipientList>';
        xml += '<Recipient>';
        xml += '<ClientName>'+dis.Name+'</ClientName>';
        xml += '<Company>'+dis.Name+'</Company>';
        xml += '<FaxNumber>'+dis.Fax__c+'</FaxNumber>';
        xml += '</Recipient>';
        xml += '</RecipientList>';
        xml += '</Body>';
        xml += '</SendFaxReq>';
        return xml;
    }
    
    
    public static String getBodyString(Order__c order,List<Order_Item__c> oItem,Distributor__c dis,Account acc)
    {
        String OrderDate,Timedelivered;
            if(order.Order_date__c!=NULL)
            {
                Date d1=order.Order_date__c;
                OrderDate=d1.year()+'-'+d1.month()+'-'+d1.day();
            }
            if(order.Time_to_delivered__c!=NULL)
            {
                Date d2=order.Time_to_delivered__c;
                Timedelivered=d2.year()+'-'+d2.month()+'-'+d2.day();
            }
            String OrderType,OrderNum,OrderUnit;
            if(order.OrderType__c=='常规')
            {
                OrderType='销售订单';
                OrderNum='订货数量';
                OrderUnit='订货单位';
            }
            else if(order.OrderType__c=='退货')
            {
                OrderType='退货订单';
                OrderNum='退货数量';
                OrderUnit='退货单位';
            }
            else if(order.OrderType__c=='免费产品')
            {
                OrderType='免费产品订单';
                OrderNum='订货数量';
                OrderUnit='订货单位';
            }
            else if(order.OrderType__c=='活动订单')
            {
                OrderType='活动订单';
                OrderNum='订货数量';
                OrderUnit='订货单位';
            }
                
            String mailBody='<Html><head><meta http-equiv="content-type" content="text/html; charset=UTF-8" /></head><body>'+dis.name+',您好！<br /> &nbsp;&nbsp;&nbsp;&nbsp;您有一批'+OrderType+'要处理,具体信息如下：<br/><br/>';
            
            mailBody+='订单基本信息：';
            mailBody+='<table cellpadding="0" cellspacing="0" style="border-color:black;border-style:solid;border-width:1px;text-align:center;width:100%">';
            //mailBody+='<tr style="border-color:black;border-style:solid;border-width:2px;"><td colspan="2" style="border-color:black;border-style:solid;border-width:2px;">基本信息</td></tr>';
            
            mailBody+='<tr style="border-color:black;border-style:solid;border-width:1px;"><td style="border-color:black;border-style:solid;border-width:1px;width:30%;">订单编号</td>';
            mailBody+='<td style="border-color:black;border-style:solid;border-width:1px;width:30%;">'+order.Name+'</td>';
            mailBody+='</tr>';
            
            mailBody+='<tr style="border-color:black;border-style:solid;border-width:1px;"><td style="border-color:black;border-style:solid;border-width:1px;width:30%;">订单类型</td>';
            mailBody+='<td style="border-color:black;border-style:solid;border-width:1px;width:30%;"><b>'+order.OrderType__c+'</b></td>';
            mailBody+='</tr>';
            
            mailBody+='<tr style="border-color:black;border-style:solid;border-width:1px;"><td style="border-color:black;border-style:solid;border-width:1px;width:30%;">门店编码</td>';
            mailBody+='<td style="border-color:black;border-style:solid;border-width:1px;width:30%;">'+acc.OutletCode__c+'</td>';
            mailBody+='</tr>';
            
            mailBody+='<tr style="border-color:black;border-style:solid;border-width:1px;"><td style="border-color:black;border-style:solid;border-width:1px;">门店名称</td>';
            mailBody+='<td style="border-color:black;border-style:solid;border-width:1px;">'+acc.name+'</td>';
            mailBody+='</tr>';
            
            mailBody+='<tr style="border-color:black;border-style:solid;border-width:1px;"><td style="border-color:black;border-style:solid;border-width:1px;">交货地址</td>';
            mailBody+='<td style="border-color:black;border-style:solid;border-width:1px;">'+order.Address__c+'</td>';
            mailBody+='</tr>';
            
            mailBody+='<tr style="border-color:black;border-style:solid;border-width:1px;"><td style="border-color:black;border-style:solid;border-width:1px;">美赞臣销售代表姓名</td>';
            mailBody+='<td style="border-color:black;border-style:solid;border-width:1px;">'+acc.Owner.name+'</td>';
            mailBody+='</tr>';
            
            mailBody+='<tr style="border-color:black;border-style:solid;border-width:1px;"><td style="border-color:black;border-style:solid;border-width:1px;">订货日期</td>';
            mailBody+='<td style="border-color:black;border-style:solid;border-width:1px;">'+OrderDate+'</td>';
            mailBody+='</tr>';
            
            mailBody+='<tr style="border-color:black;border-style:solid;border-width:1px;"><td style="border-color:black;border-style:solid;border-width:1px;">交货日期</td>';
            mailBody+='<td style="border-color:black;border-style:solid;border-width:1px;">'+Timedelivered+'</td>';
            mailBody+='</tr>';
            
            mailBody+='<tr style="border-color:black;border-style:solid;border-width:1px;"><td style="border-color:black;border-style:solid;border-width:1px;">建议供货含税单价(箱)</td>';
            mailBody+='<td style="border-color:black;border-style:solid;border-width:1px;">'+order.Total_value__c+'</td>';
            mailBody+='</tr>';
            
            mailBody+='</table>';
            
            //mailBody+='<table cellpadding="0" cellspacing="0" style="border-color:black;border-style:solid;border-width:1px;text-align:center;width:100%">';
            //mailBody+='<tr style="border-color:black;border-style:solid;border-width:1px;"><td style="border-color:black;border-style:solid;border-width:1px;">订购产品信息</td></tr>';
            //mailBody+='</table>';
            mailBody+='<br /><br/>';
            mailBody+='订购产品信息：';
            mailBody+='<table cellpadding="0" cellspacing="0" style="border-color:black;border-style:solid;border-width:1px;text-align:center;width:100%">';
            
            //mailBody+='<tr style="border-color:black;border-style:solid;border-width:1px;"><td colspan="3" style="border-color:black;border-style:solid;border-width:1px;>订购产品信息</td></tr>';
            mailBody+='<tr style="border-color:black;border-style:solid;border-width:1px;" >';
            mailBody+='<td style="border-color:black;border-style:solid;border-width:1px;width:5%;" >序号</td>';
            mailBody+='<td style="border-color:black;border-style:solid;border-width:1px;width:15%;" >产品名称</td>';
            mailBody+='<td style="border-color:black;border-style:solid;border-width:1px;width:10%;" >产品条码</td>';
            mailBody+='<td style="border-color:black;border-style:solid;border-width:1px;width:15%;">规格</td>';
            mailBody+='<td style="border-color:black;border-style:solid;border-width:1px;width:15%;">'+OrderUnit+'</td>';
            mailBody+='<td style="border-color:black;border-style:solid;border-width:1px;width:15%;">'+OrderNum+'</td>';//订货数量
            if(order.OrderType__c!='活动订单')
                mailBody+='<td style="border-color:black;border-style:solid;border-width:1px;width:18%;">建议供货含税单价(箱)</td>';
            
            if(order.OrderType__c=='退货')
            {
                mailBody+='<td style="border-color:black;border-style:solid;border-width:1px;width:25%;">退货原因</td>';
            }
            mailBody+='</tr>';
            Integer iNum=0;
            for(Order_Item__c oi:oItem)
            {
                iNum++;
                Product2 pro=[select Name,Product_Unit_Volume__c,Barcode__c,Distributor_Listing_Price_After_Tax__c,Pack_Size_C__c from Product2 where Id=:oi.Product_Name__c];
                mailBody+='<tr style="border-color:black;border-style:solid;border-width:1px;" >';
                mailBody+='<td style="border-color:black;border-style:solid;border-width:1px;" >'+iNum+'</td>';
                mailBody+='<td style="border-color:black;border-style:solid;border-width:1px;" >'+pro.name+'</td>';
                mailBody+='<td style="border-color:black;border-style:solid;border-width:1px;" >'+pro.Barcode__c+'</td>';
                mailBody+='<td style="border-color:black;border-style:solid;border-width:1px;" >'+pro.Product_Unit_Volume__c+'×'+pro.Pack_Size_C__c+'</td>';
                if(order.OrderType__c!='活动订单')    
                {
                    mailBody+='<td style="border-color:black;border-style:solid;border-width:1px;">'+oi.RealPackage__c+'</td>';
                    mailBody+='<td style="border-color:black;border-style:solid;border-width:1px;">'+oi.RealItemNumber__c+'</td>';
                }
                else
                {
                    mailBody+='<td style="border-color:black;border-style:solid;border-width:1px;">个</td>';
                    mailBody+='<td style="border-color:black;border-style:solid;border-width:1px;">'+oi.OrderNumber__c+'</td>';
                 }
                
                if(order.OrderType__c!='活动订单')
                    mailBody+='<td style="border-color:black;border-style:solid;border-width:1px;">'+oi.Price_after_tax__c+'</td>';
                if(order.OrderType__c=='退货')
                {
                    String OrderReason='';
                    if(oi.Return_Reason__c!=NULL)
                        OrderReason=':'+oi.Return_Reason__c;
                    mailBody+='<td style="border-color:black;border-style:solid;border-width:1px;">'+oi.ReturnReasonList__c+OrderReason+'</td>';
                }
                mailBody+='</tr>';
            }
           
            mailBody+='</table>';
            mailBody+='</body></html>';
            
            return mailBody;
    }
    
    public static void SendOrderToApproval(Order__c order)
    {
        User u=[select id,username,ManagerId,Title__c from User where id=:UserInfo.getUserId()];
        if(order.OrderType__c=='退货' || order.OrderType__c=='免费产品' || order.OrderType__c=='活动订单')
        {            
            if (u.ManagerId != null)            
            {                 
                Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();                 
                req1.setObjectId(order.id);
                // Submit the approval request for the account
                Approval.ProcessResult result = Approval.process(req1);  
            }        
         }
    }
    
    static testmethod void test()
    {
        Profile p = [select id from profile where name='System Administrator' or Name='系统管理员'];
        User u = new User(alias = 'standtss', email='standarduser@testorgss.com',
        emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
        localesidkey='en_US', profileid = p.Id,title__c='DSM',
        timezonesidkey='America/Los_Angeles', username='standardusers@testorg.com');
        insert u;
        
        User u2 = new User(alias = 'test', email='ddd@testorgss.com',
        emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
        localesidkey='en_US', profileid = p.Id,title__c='DSM',ManagerId=u.Id,
        timezonesidkey='America/Los_Angeles', username='44444@testorg.com');
        insert u2;
        System.runAs(u2)
        {
            Product2 ps=new Product2();
            ps.Name='testProduct';
            insert ps;
            
            Account acc=new Account();
            acc.Name='test';
            acc.Channel__c='百货店';
            acc.Contact__c='aaa';
            acc.No_of_checkout__c=22;
            acc.ContactPhoneNumber__c='1234567456';
            insert acc;
            
            Distributor__c dis=new Distributor__c(Distributor_Code__c='wwwwwww',Name='test',Fax__c='111111',Address__c='ddddd',Phone__c='123344',Accepted_Order_Way__c='Fax',Email__c='aa@aa.com');
            insert dis;
            
            Distributor__c dis2=new Distributor__c(Distributor_Code__c='dddd',Name='test',Fax__c='111111',Address__c='ddddd',Phone__c='123344',Accepted_Order_Way__c='Email',Email__c='aa@aa.com');
            insert dis2;
            
            Routing_Plan_And_Visit__c tr=new Routing_Plan_And_Visit__c(Visit_Date__c=Date.today().addMonths(1));
            insert tr;
            
            RoutingPlan__c rp=new RoutingPlan__c();
            rp.RoutingPlanAndVisit__c=tr.Id;
            rp.OutletName__c=acc.Id;
            Date d=tr.Visit_Date__c;
            rp.StartDateTime__c=DateTime.newInstance(d.year(),d.month(),d.day(),8,8,8);
            rp.EndDateTime__c=DateTime.newInstance(d.year(),d.month(),d.day(),9,9,9);
            insert rp;
            
            In_Store_Visit__c vi=new In_Store_Visit__c();
            vi.RoutingPlanAndVisit__c=tr.Id;
            vi.OutletName_del__c=acc.Id;
            vi.Start_Time__c=DateTime.newInstance(d.year(),d.month(),d.day(),8,8,8);
            vi.End_Time__c=DateTime.newInstance(d.year(),d.month(),d.day(),9,9,9);
            vi.Main_Shelf_Facing__c=22;
            insert vi;
            
            Order__c ord=new Order__c();   
            ord.Outlet_name__c=acc.Id;
            ord.OrderType__c='return';
            ord.In_Store_Visit__c=vi.Id;
            ord.Distributor_Name__c=dis.Id;
            ord.Approval__c=false;
            ord.Address__c='asfsdfdf';
            insert ord;
             
            Order_Item__c item=new Order_Item__c();
            item.Order_Name__c=ord.Id;
            item.OrderNumber__c=44;
            item.Product_Name__c=ps.Id;
            item.Return_Reason__c='saddfdf';
            item.Price_after_tax__c=333;
            insert item;
            
            List<Order_Item__c> ol=new List<Order_Item__c>();
            ol.add(item);
            SendOrder.SendOrderToDistributor(ord.Id);
            SendOrder.SendMail(ord, ol,dis2,acc);
            SendOrder.SendOrderToApproval(ord);
            
            ord.ItemsDone__c=true;
           
            update ord;
             
        }
        
       /* Id d='a0KO000000005z2MAA';
        Order__c order=[Select o.Order_date__c,o.Time_to_delivered__c,o.OrderType__c,o.Outlet_name__c,o.Distributor_Name__c,o.Name, o.Id 
        From Order__c o where o.Id='a0KO000000007Lg'];       
        List<Order_Item__c> oItem=[select Id,Product_Name__c,OrderNumber__c,Return_Reason__c,Product_Name__r.Product_Unit_Volume__c from Order_Item__c where Order_Name__c='a0KO000000007Lg']; 
        SendOrder.SendOrderToDistributor(order,oItem);*/
    }
}